<template>
	<p>
		自定义链接组件：我们创建了 useLink 组件替代标准的 <router-link></router-link>，使用按钮元素实现导航<br />
		父子通信：<br />
		    ○ 父组件通过 props 传递 to 和 showBadge 给子组件<br />
		    ○ 子组件通过 emit 触发 before-navigate 事件，父组件可以拦截导航<br />
		useLink 使用：<br />
		    ○ 将 props.to 包装为计算属性传递给 useLink<br />
		    ○ 使用返回的 isActive 和 isExactActive 控制激活状态样式<br />
		    ○ 通过 navigate 方法实现导航<br />
		样式控制：<br />
		    ○ 根据 isActive 和 isExactActive 添加不同样式类<br />
		    ○ 使用 showBadge 属性控制是否显示激活标记
	</p>
	<button @click="handleClick" :class="[
      'custom-link',
      { 
        active: isActive,
        'exact-active': isExactActive 
      }
    ]" :aria-current="isActive ? 'page' : undefined">
		<slot />
		<span v-if="showBadge && isActive" class="badge">当前</span>
	</button>
</template>

<script setup>
	import {
		useLink
	} from 'vue-router'
	import {
		computed
	} from 'vue'

	const props = defineProps({
		to: {
			type: [String, Object],
			required: true
		},
		showBadge: {
			type: Boolean,
			default: false
		}
	})

	const emit = defineEmits(['before-navigate'])

	const {
		route,
		href,
		isActive,
		isExactActive,
		navigate
	} = useLink({
		to: computed(() => props.to)
	})
	console.log(
		route,
		href,
		isActive,
		isExactActive,
		navigate
	)

	const handleClick = async (event) => {
		console.log('handleClick: ', event)
		// 触发 before-navigate 事件
		const shouldNavigate = emit('before-navigate', props.to)

		// 如果父组件返回false，阻止导航
		if (shouldNavigate === false) return

		// 可以在这里添加自定义逻辑
		console.log('导航前执行:', props.to)

		// 调用导航
		navigate(event)
	}
</script>

<style scoped>
	.custom-link {
		padding: 0.5rem 1rem;
		border: none;
		background: none;
		cursor: pointer;
		font-size: 1rem;
		position: relative;
	}

	.custom-link:hover {
		background: #e0e0e0;
	}

	.custom-link.active {
		font-weight: bold;
		color: #42b983;
	}

	.custom-link.exact-active {
		border-bottom: 2px solid #42b983;
	}

	.badge {
		position: absolute;
		top: -8px;
		right: -8px;
		background: #42b983;
		color: white;
		border-radius: 50%;
		width: 16px;
		height: 16px;
		font-size: 0.7rem;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>